package com.lmh.ymw.service.order;

import com.lmh.ymw.entity.Product;
import com.lmh.ymw.mapper.order.OrderDao;
import com.lmh.ymw.mapper.order.OrderDetailDao;
import com.lmh.ymw.mapper.product.ProductDao;
import com.lmh.ymw.utils.ShoppingCartItem;
import com.lmh.ymw.utils.StringUtils;
import com.lmh.ymw.entity.Order;
import com.lmh.ymw.entity.OrderDetail;
import com.lmh.ymw.entity.User;
import com.lmh.ymw.utils.ShoppingCart;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class OrderServiceImpl implements OrderService{
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private ProductDao productDao;
    @Autowired
    private OrderDetailDao orderDetailDao;
    @Override
    public Order payShoppingCart(ShoppingCart cart, User user, String address) {
        Order order = new Order();
        order.setUserId(user.getId());
        order.setLoginName(user.getLoginName());
        order.setUserAddress(address);
        order.setCreateTime(new Date());
        order.setCost(cart.getTotalCost());
        order.setSerialNumber(StringUtils.randomUUID());
        //增加订单对应的明细信息
        for (ShoppingCartItem item : cart.getItems()) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(order.getId());
            orderDetail.setCost(item.getCost());
            orderDetail.setProduct(item.getProduct());
            orderDetail.setQuantity(item.getQuantity());
            orderDetailDao.insert(orderDetail);

            //更新商品表的库存
            Product product=new Product();
            product.setId(item.getProduct().getId());
            product.setStock(item.getQuantity());
            productDao.updateByPrimaryKeySelective(product);
        }
        return order;
    }

    @Override
    public List<Order> getOrderList(Integer userId) {
        List<Order> orderList = orderDao.getOrderList(userId);
        for (Order order : orderList) {
            order.setOrderDetailList(orderDetailDao.getOrderDetailList(order.getId()));
        }
        return orderList;
    }

    @Override
    public List<OrderDetail> getOrderDetailList(Integer orderId) {
        List<OrderDetail> orderDetailList = orderDetailDao.getOrderDetailList(orderId);
        return orderDetailList;
    }
}
